import CryptoJS from 'crypto-js';

const key = CryptoJS.enc.Utf8.parse('ccbimtestpinming');
const IV = CryptoJS.enc.Utf8.parse('cn.pinming699899');

// AES加密
export function encryptByAES(data: any) {
  const jsonData = JSON.stringify(data);
  const encrypted = CryptoJS.AES.encrypt(jsonData, key, {
    iv: IV,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  const finEncrypted = encrypted.toString();
  return finEncrypted;
}
// AES解密
export function decryptedByAES(data: any) {
  if (data && data.type != 'webpackOk') {
    let decryptedData = CryptoJS.AES.decrypt(data, key, {
      iv: IV,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });

    decryptedData = JSON.parse(decryptedData.toString(CryptoJS.enc.Utf8));
    return decryptedData;
  }
  return {};
}

// 客户端操作web端的同步类型
type OperationType =
  | 'setFolderStatus' // 文件同步点击目录
  | 'changePath' // 修改页面类型
  | 'setUpLoading' // 设置上传同步状态
  | 'setHistroyList'; // 修改页面类型

function sendMessageToIframe(iframeRef: any, key: OperationType, data: any) {
  const dealData = { key, data: data || {} };
  const enData = encryptByAES(dealData);
  iframeRef?.current?.contentWindow?.postMessage(enData, '*');
}

// 传递数据到web端直接调用该方法
export const sendMessage = {
  // 文件夹同步状态
  setFolderStatus: (iframeRef: any, data: any) => {
    sendMessageToIframe(iframeRef, 'setFolderStatus', data);
  },

  setHistroyList: (iframeRef: any, data: any) => {
    sendMessageToIframe(iframeRef, 'setHistroyList', data);
  },

  setUpLoading: (iframeRef: any, data: any) => {
    sendMessageToIframe(iframeRef, 'setUpLoading', data);
  },
};

// 客户端操作web端的同步类型
const operationFnKeys: any = {
  login: 'login',
  logout: 'logout',
  synchronous: 'synchronous',
  renderFinish: 'renderFinish',
  openBrowser: 'openBrowser',
  setPath: 'setPath', // 打开弹窗
  openFolder: 'openFolder', // 打开弹窗
  getFolderStatus: 'getFolderStatus', // 打开弹窗
  upload: 'upload', // 打开弹窗
};

// 注册连接通道
export const registerBridge = (callback: any) => {
  window.addEventListener('message', (event) => {
    const message = event.data;
    const { origin } = event;
    const baseOrigin = window.electron.store.get('baseOrigin');
    // 只接收指定源处理
    if (origin === baseOrigin) {
      const data = decryptedByAES(message);
      if (operationFnKeys[data.key] != undefined) {
        callback(data.data, operationFnKeys[data.key]);
      }
    }
  });
};
